package com.woniu113.junk.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu113.junk.order.client.SiteClient;
import com.woniu113.junk.order.client.UserClient;
import com.woniu113.junk.order.client.dto.AdminInfo;
import com.woniu113.junk.order.client.dto.AdminInfoDTO;
import com.woniu113.junk.order.client.dto.StationInfoDTO;
import com.woniu113.junk.order.dto.AllPerformanceInfoDTO;
import com.woniu113.junk.order.dto.PerformanceInfoDTO;
import com.woniu113.junk.order.exception.PerformanceInfoException;
import com.woniu113.junk.order.mapper.OrderInfoMapper;
import com.woniu113.junk.order.mapper.StatisticsInfoMapper;
import com.woniu113.junk.order.model.OrderInfo;
import com.woniu113.junk.order.model.PerformanceInfo;
import com.woniu113.junk.order.mapper.PerformanceInfoMapper;
import com.woniu113.junk.order.model.StatisticsInfo;
import com.woniu113.junk.order.param.performanceInfo.FindAllPerformanceParam;
import com.woniu113.junk.order.param.performanceInfo.FindByRiderIdParam;
import com.woniu113.junk.order.service.OrderInfoService;
import com.woniu113.junk.order.service.PerformanceInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu113.junk.order.util.Data;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 蜡笔没了小新
 * @since 2024年10月16日
 */
@Service
public class PerformanceInfoServiceImpl extends ServiceImpl<PerformanceInfoMapper, PerformanceInfo> implements PerformanceInfoService {
    @Resource
    private OrderInfoService ois;
    @Resource
    private PerformanceInfoService pis;
    @Resource
    private PerformanceInfoMapper pim;
    @Resource
    private StatisticsInfoMapper sim;
    @Resource
    private SiteClient sc;
    @Resource
    private UserClient userClient;

    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Override
    public void normalAdd(String orderNum) {
        //判断传入参数是否正确
        OrderInfo orderInfo = ois.getById(orderNum);

        System.out.println("订单入库状态"+orderInfo.getStockState());
        System.out.println("状态"+orderInfo.getState());

        if (orderInfo == null || orderInfo.getStockState() != Data.STOCK_STATE_NOT_IN_STOCK || orderInfo.getState() != Data.ORDER_INFO_STATE_NORMAL) {
            throw new PerformanceInfoException("订单不存在",5401);
        }

        orderInfo.setStockState(Data.STOCK_STATE_IN_STOCK);
        orderInfoMapper.updateById(orderInfo);

        Integer riderId = orderInfo.getRiderId();
        LocalDateTime orderEndTime = orderInfo.getOrderEndTime();
        // 将 LocalDateTime 转换为 LocalDate
        LocalDate date = orderEndTime.toLocalDate();

        //查询骑手订单统计数据
        QueryWrapper<PerformanceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",riderId).eq("date",date);
        PerformanceInfo performanceInfo = pim.selectOne(queryWrapper);
        //查询站点订单统计数据
        QueryWrapper<StatisticsInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",orderInfo.getStationId()).eq("date",date);
        StatisticsInfo statisticsInfo = sim.selectOne(wrapper);
        //查询子站点对应区站点
        StationInfoDTO data = sc.findFatherStationById(orderInfo.getStationId()).getData();

        if (performanceInfo == null){
            //新增骑手绩效记录
            PerformanceInfo info = new PerformanceInfo();
            info.setUserId(riderId);
            info.setDate(date);
            info.setTotalNum(1);
            info.setEffectiveNum(1);
            pis.save(info);
            //判断站点站点订单统计数据是否需要新增
            if (statisticsInfo == null){
                //新增
                StatisticsInfo info1 = new StatisticsInfo();
                info1.setStationId(orderInfo.getStationId());
                info1.setCountyStationId(data.getStationId());
                info1.setDate(date);
                info1.setTotalNum(1);
                info1.setEffectiveNum(1);
                sim.insert(info1);
            }else {
                //修改
                statisticsInfo.setTotalNum(statisticsInfo.getTotalNum()+1);
                statisticsInfo.setEffectiveNum(statisticsInfo.getEffectiveNum()+1);
                sim.updateById(statisticsInfo);
            }
        }else {
            //修改
            performanceInfo.setTotalNum(performanceInfo.getTotalNum()+1);
            performanceInfo.setEffectiveNum(performanceInfo.getEffectiveNum()+1);
            pim.updateById(performanceInfo);
            //判断站点站点订单统计数据是否需要新增
            if (statisticsInfo == null){
                //新增
                StatisticsInfo info1 = new StatisticsInfo();
                info1.setStationId(orderInfo.getStationId());
                info1.setCountyStationId(data.getStationId());
                info1.setDate(date);
                info1.setTotalNum(1);
                info1.setEffectiveNum(1);
                sim.insert(info1);
            }else {
                //修改
                statisticsInfo.setTotalNum(statisticsInfo.getTotalNum()+1);
                if (statisticsInfo.getEffectiveNum()==null){
                    statisticsInfo.setEffectiveNum(1);
                }else {
                    statisticsInfo.setEffectiveNum(statisticsInfo.getEffectiveNum()+1);
                }
                sim.updateById(statisticsInfo);
            }
        }
    }

    @Override
    public void abnormalAdd(String orderNum) {
        //判断传入参数是否正确
        OrderInfo orderInfo = ois.getById(orderNum);

        System.out.println("订单入库状态"+orderInfo.getStockState());
        System.out.println("状态"+orderInfo.getState());

        if (orderInfo == null || orderInfo.getStockState() != Data.STOCK_STATE_NOT_IN_STOCK || orderInfo.getState() != Data.ORDER_INFO_STATE_NORMAL) {
            throw new PerformanceInfoException("订单不存在",5401);
        }
        orderInfo.setStockState(Data.STOCK_STATE_VERIFICATION_FAILED);
        orderInfoMapper.updateById(orderInfo);

        Integer riderId = orderInfo.getRiderId();
        LocalDateTime orderEndTime = orderInfo.getOrderEndTime();
        // 将 LocalDateTime 转换为 LocalDate
        LocalDate date = orderEndTime.toLocalDate();

        //查询骑手订单统计数据
        QueryWrapper<PerformanceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",riderId).eq("date",date);
        PerformanceInfo performanceInfo = pim.selectOne(queryWrapper);
        //查询站点订单统计数据
        QueryWrapper<StatisticsInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",orderInfo.getStationId()).eq("date",date);
        StatisticsInfo statisticsInfo = sim.selectOne(wrapper);
        //查询子站点对应区站点
        StationInfoDTO data = sc.findFatherStationById(orderInfo.getStationId()).getData();

        if (performanceInfo == null){
            PerformanceInfo info = new PerformanceInfo();
            info.setUserId(riderId);
            info.setDate(date);
            info.setTotalNum(1);
            info.setAbnormalNum(1);
            pis.save(info);
            if (statisticsInfo == null){
                StatisticsInfo statisticsInfo1 = new StatisticsInfo();
                statisticsInfo1.setDate(LocalDate.now());
                statisticsInfo1.setStationId(orderInfo.getStationId());
                statisticsInfo1.setTotalNum(1);
                statisticsInfo1.setCountyStationId(data.getStationId());
                statisticsInfo1.setAbnormalNum(1);
                sim.insert(statisticsInfo1);
            }else {
                if (statisticsInfo.getAbnormalNum() == null){
                    statisticsInfo.setAbnormalNum(1);
                }else {
                    statisticsInfo.setAbnormalNum(statisticsInfo.getAbnormalNum()+1);
                }
                statisticsInfo.setTotalNum(statisticsInfo.getTotalNum()+1);
                sim.updateById(statisticsInfo);
            }
        }else {
            performanceInfo.setTotalNum(performanceInfo.getTotalNum()+1);
            performanceInfo.setAbnormalNum(performanceInfo.getAbnormalNum()+1);
            pim.updateById(performanceInfo);
            if (statisticsInfo == null){
                StatisticsInfo statisticsInfo1 = new StatisticsInfo();
                statisticsInfo1.setDate(LocalDate.now());
                statisticsInfo1.setStationId(orderInfo.getStationId());
                statisticsInfo1.setTotalNum(1);
                statisticsInfo1.setCountyStationId(data.getStationId());
                statisticsInfo1.setAbnormalNum(1);
                sim.insert(statisticsInfo1);
            }else {
                if (statisticsInfo.getAbnormalNum() == null){
                    statisticsInfo.setAbnormalNum(1);
                }else {
                    statisticsInfo.setAbnormalNum(statisticsInfo.getAbnormalNum()+1);
                }
                statisticsInfo.setTotalNum(statisticsInfo.getTotalNum()+1);
                sim.updateById(statisticsInfo);
            }
        }
    }

    @Override
    public Page<PerformanceInfo> findByRiderId(FindByRiderIdParam param) {
        Page<PerformanceInfo> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<PerformanceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",param.getRiderId());
        Page<PerformanceInfo> infoPage = pim.selectPage(page, queryWrapper);
        return infoPage;
    }

    @Override
    public AllPerformanceInfoDTO findAll(FindAllPerformanceParam param) {
        Integer adminId= null;
        if (param.getAdminName()!=null && !param.getAdminName().equals("")){//不为空,查id
            Integer adminId1 = userClient.selectAdminByAdminName(param.getAdminName()).getData().getAdminId();
            adminId =adminId1;
        }
        QueryWrapper<PerformanceInfo> queryWrapper = new QueryWrapper<>();
        if (adminId!=null){
            queryWrapper.eq("user_id",adminId);
        }
        int offset = (param.getPageNum() - 1) * param.getPageSize();
        int size = Math.toIntExact(pim.selectCount(queryWrapper)); // 获取符合条件的总记录数
        queryWrapper.last("LIMIT " + offset + ", " + param.getPageSize());
        List<PerformanceInfo> infos = pim.selectList(queryWrapper);

        ArrayList<PerformanceInfoDTO> performanceInfoDTOS = new ArrayList<>();
        for (PerformanceInfo performanceInfo : infos) {
            AdminInfoDTO adminInfoDTO = userClient.selectAdminById(performanceInfo.getUserId()).getData();
            PerformanceInfoDTO performanceInfoDTO = BeanUtil.toBean(performanceInfo, PerformanceInfoDTO.class);
            performanceInfoDTO.setAdminName(adminInfoDTO.getAdminName());
            performanceInfoDTO.setRealName(adminInfoDTO.getRealName());
            performanceInfoDTO.setAdminPhone(adminInfoDTO.getAdminPhone());
            performanceInfoDTOS.add(performanceInfoDTO);
        }
        AllPerformanceInfoDTO dto = new AllPerformanceInfoDTO();
        dto.setList(performanceInfoDTOS);
        dto.setTotal(size);
        return dto;
    }
}
